<script>
import QRious from "qrious";

export default {
  props: {
    value: {
      type: null,
      required: true
    },
    /*
     * 选项，参考.
     * {@link https://github.com/lindell/JsQrcode#options}
     */
    options: {
      type: Object,
      default: {}
    },

    /*
     * 渲染类型：canvas，img.
     */
    tag: {
      type: String,
      default: "canvas"
    }
  },

  render(createElement) {
    return createElement(this.tag, this.$slots.default);
  },

  watch: {
    value() {
      this.generate();
    },
    options() {
      this.generate();
    }
  },

  mounted() {
    this.generate();
  },

  methods: {
    generate() {
      new QRious(
        Object.assign(
          {
            element: this.$el,
            value: String(this.utf16to8(this.value))
          },
          this.options
        )
      );
      if (
        this.$slots.logo &&
        this.$slots.logo[0] &&
        this.$slots.logo[0].data.attrs.src
      ) {
        let size = this.options.size || 100;
        this.$el
          .getContext("2d")
          .drawImage(
            this.$$(
              '<img src="' + this.$slots.logo[0].data.attrs.src + '"></img>'
            )[0],
            size * 0.4,
            size * 0.4,
            size * 0.2,
            size * 0.2
          );
      }
    },
    utf16to8(str) {
      var out, i, len, c;
      out = "";
      len = str.length;
      for (i = 0; i < len; i++) {
        c = str.charCodeAt(i);
        if (c >= 0x0001 && c <= 0x007f) {
          out += str.charAt(i);
        } else if (c > 0x07ff) {
          out += String.fromCharCode(0xe0 | ((c >> 12) & 0x0f));
          out += String.fromCharCode(0x80 | ((c >> 6) & 0x3f));
          out += String.fromCharCode(0x80 | ((c >> 0) & 0x3f));
        } else {
          out += String.fromCharCode(0xc0 | ((c >> 6) & 0x1f));
          out += String.fromCharCode(0x80 | ((c >> 0) & 0x3f));
        }
      }
      return out;
    }
  }
};
</script>